package com.xhj.bigfactory.bigFactory.Lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import static java.lang.System.out;
/**
 * -
 *
 * @author 周沫 @Date 2021-07-31 @Time 16:57
 *     <p>多线程之间顺序调用A->B->C，要求： A打印5次，B10次，C15次， 来5轮。
 */
public class SyncReentrantLockDemo {

  // 线程操纵资源类
  private static class Data {
    private int number = 1;
    ReentrantLock lock = new ReentrantLock(true);
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();

    public void print5() {
      lock.lock();
      try {
        // 判断
        while (number != 1) {
          c1.await();
        }
        // 干活
        out.print(Thread.currentThread().getName() + ": ");
        for (int i = 0; i < 5; i++) {
          out.print('a');
        }
        out.print("\n");
        // 通知
        number = 2;
        c2.signal();
      } catch (Exception e) {
        out.println(e);
      } finally {
        lock.unlock();
      }
    }

    public void print10() {
      lock.lock();
      try {
        // 判断
        while (number != 2) {
          c2.await();
        }
        // 干活
        out.print(Thread.currentThread().getName() + ": ");
        for (int i = 0; i < 10; i++) {
          out.print('b');
        }
        out.print("\n");
        // 通知
        number = 3;
        c3.signal();
      } catch (Exception e) {
        out.println(e);
      } finally {
        lock.unlock();
      }
    }

    public void print15() {
      lock.lock();
      try {
        // 判断
        while (number != 3) {
          c3.await();
        }
        // 干活
        out.print(Thread.currentThread().getName() + ": ");
        for (int i = 0; i < 15; i++) {
          out.print('c');
        }
        out.print("\n");
        // 通知
        number = 1;
        c1.signal();
      } catch (Exception e) {
        out.println(e);
      } finally {
        lock.unlock();
      }
    }
  }

  public static void main(String[] args) {
    Data data = new Data();
    new Thread(
            () -> {
              for (int i = 0; i < 5; i++) {
                data.print5();
              }
            },
            "AAA")
        .start();
    new Thread(
            () -> {
              for (int i = 0; i < 5; i++) {
                data.print10();
              }
            },
            "BBB")
        .start();
    new Thread(
            () -> {
              for (int i = 0; i < 5; i++) {
                data.print15();
              }
            },
            "CCC")
        .start();
  }
}
